package com.xiaofu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaofu.interceptor.LoginInterceptor;
import com.xiaofu.mapper.CouponRecordMapper;
import com.xiaofu.model.CouponRecordDO;
import com.xiaofu.model.LoginUser;
import com.xiaofu.service.CouponRecordService;
import com.xiaofu.vo.CouponRecordVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 小夫
 * @since 2024-07-18
 */
@Service
@Slf4j
public class CouponRecordServiceImpl implements CouponRecordService {

    @Autowired
    private CouponRecordMapper couponRecordMapper;

    @Override
    /**
     * 分页查询领券记录
     */
    public Map<String, Object> page(int page, int size) {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        Page<CouponRecordDO> pageInfo = new Page<>(page, size);
        IPage<CouponRecordDO> pageResult = couponRecordMapper.selectPage(pageInfo, new LambdaQueryWrapper<CouponRecordDO>()
                .eq(CouponRecordDO::getUserId, loginUser.getId())
                .orderByDesc(CouponRecordDO::getCreateTime));
        Map<String, Object> pageMap = new HashMap<>(3);
        pageMap.put("total_record", pageResult.getTotal());
        pageMap.put("current_data", beansProcess(pageResult.getRecords()));
        pageMap.put("total_page", pageResult.getPages());
        return pageMap;
    }

    /**
     * 查询优惠券记录详情
     * @param recordId
     * @return
     */
    @Override
    public CouponRecordVO findById(Long recordId) {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        CouponRecordDO couponRecordDO = couponRecordMapper.selectOne(new LambdaQueryWrapper<CouponRecordDO>()
                .eq(CouponRecordDO::getUserId, loginUser.getId())
                .eq(CouponRecordDO::getId, recordId));
        if (couponRecordDO == null) {
            return null;
        }
        CouponRecordVO couponRecordVO = new CouponRecordVO();
        BeanUtils.copyProperties(couponRecordDO, couponRecordVO);
        return couponRecordVO;
    }

    private List<CouponRecordVO> beansProcess(List<CouponRecordDO> records) {
        return records.stream().map(item -> {
            CouponRecordVO couponRecordVO = new CouponRecordVO();
            BeanUtils.copyProperties(item, couponRecordVO);
            return couponRecordVO;
        }).collect(Collectors.toList());
    }
}
